package uk.ac.salfordcc.sccmobile;

import android.*;
import android.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;

// These are utilities and methods that can be called from any Activity.
public class SharedUtilities extends Activity {
    private Context mContext;

    SharedUtilities(Context context){
        // Class Constructor
        this.mContext = context;
    }
	public static void endApplication(final Activity caller, final Context c){
		// Display a dialog to ask the user if they would like to confirm that they
    	// intend to finish the activity.
    	new AlertDialog.Builder(caller)
		.setMessage("Are you sure you want to exit?")
		.setCancelable(true)
		.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog, int id){
                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext());
                SharedPreferences.Editor ed = sp.edit();
                ed.remove("PIN_EXP").commit();
				caller.finishAffinity();	// End all activities associated with the application.
			}
		})
		.setNegativeButton("No", null)
		.show();
	}

    public final String getStoredPreference(final String Key){
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this.mContext);
        String storedValue = sp.getString(Key, ""); //returns "" if not stored.

        Log.e("scc: [SharedUtilities/getStoredPreferences] ", storedValue);
        return storedValue;
    }

    public static void checkSessionPIN(final Activity caller, final Context c){
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext());
        Long expiration = sp.getLong("PIN_EXP", 0);
        Long current = System.currentTimeMillis();
        if(current > expiration){
            Intent intent = new Intent(caller, PINActivity.class);
            c.startActivity(intent);
        }
    }

    public static void clearPinExpiration(Context app){
        // If the back button is pressed on this screen, then the PIN session expiration is cleared.
        // This will force the application to ask for it onResume.
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(app.getApplicationContext());
        SharedPreferences.Editor ed = sp.edit();
        ed.remove("PIN_EXP");
        ed.commit();
    }

}

